<template>
  <el-card>
    <el-row :gutter="20">
      <el-col :span="5">
        <!-- 左侧标签分类 -->
        <div class="flex flex-col">
          <el-button type="warning" icon="Plus" class="mb-2.5" @click="addCategory(true)">新增分类</el-button>
          <div
              class="flex items-center cursor-pointer pa-1.5"
              :class="{'active-tag-cate': item.id === activeTagCate}"
              v-for="item in tagCateList"
              :key="item.id"
              @click="handleClickTagCate(item.id)"
          >
            <el-icon size="24" class="mr-2.5">
              <myIconFolder/>
            </el-icon>
            <el-text size="large">{{ item.cate_name }}</el-text>
            <el-dropdown class="ml-auto">
              <span>
                <el-icon>
                  <MoreFilled/>
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="addCategory(false, item)">编辑分类</el-dropdown-item>
                  <el-dropdown-item @click="handleDeleteCate(item)">删除分类</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-col>
      <el-col :span="19">
        <!-- 数据表格 -->
        <div class="table-container">
          <div class="mb-2.5">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-button type="primary" :icon="CirclePlus" @click="openDialogForm(true)">新增</el-button>
              </el-col>
              <el-col :span="12">
                <div class="flex justify-end">
                  <el-button :icon="RefreshRight" circle @click="handleRefresh"></el-button>
                </div>
              </el-col>
            </el-row>
          </div>
          <div class="table-wrapper">
            <el-table :data="tableData" style="width: 100%;">
              <el-table-column align="center" prop="id" label="ID"></el-table-column>
              <el-table-column align="center" prop="tag_name" label="标签名称"></el-table-column>
              <el-table-column align="center" prop="userTagCate.cate_name" label="分类名称"></el-table-column>
              <el-table-column align="center" label="状态">
                <template #default="scope">
                  <el-tag :type="getStatusInfo(scope.row.status).type">
                    {{ getStatusInfo(scope.row.status).text }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作">
                <template #default="scope">
                  <el-button type="primary" link @click="openDialogForm(false, scope.row)">编辑</el-button>
                  <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!-- 分页组件 -->
          <div class="py-5 px-0 flex justify-end">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                           :page-sizes="[15, 30, 50, 100]"
                           :disabled="false" background layout="total, sizes, prev, pager, next, jumper"
                           :total="total"
                           @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
          </div>
        </div>
      </el-col>
    </el-row>
    <!-- 新增标签 -->
    <el-dialog v-model="formShow" :title="dialogTitle">
      <el-form ref="formDataRef" class="pa-5" :rules="rules" :model="formData" label-position="right"
               label-width="auto">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="标签名称" prop="tag_name">
              <el-input v-model="formData.tag_name" placeholder="请输入标签名称" autocomplete="off"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="标签分类" prop="cate_id">
              <el-select
                  v-model="formData.cate_id"
                  placeholder="选择标签分类"
              >
                <el-option
                    v-for="item in tagCateList"
                    :key="item.id"
                    :label="item.cate_name"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio :value="1">启用</el-radio>
                <el-radio :value="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增分类 -->
    <el-dialog v-model="formCateShow" :title="dialogCateTitle">
      <el-form ref="formCateDataRef" class="pa-5" :rules="cateRules" :model="formCateData" label-position="right"
               label-width="auto">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="分类名称" prop="cate_name">
              <el-input v-model="formCateData.cate_name" placeholder="请输入分类名称" autocomplete="off"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="formCateData.sort" placeholder="请输入分类名称" autocomplete="off"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseCate">取消</el-button>
          <el-button type="primary" @click="handleCateSubmit()">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref, computed, nextTick} from 'vue';
import {ElMessage, ElMessageBox, type FormInstance, type FormRules} from 'element-plus'
import {RefreshRight, CirclePlus, MoreFilled} from '@element-plus/icons-vue'
import {
  getUserTagCateListApi,
  getUserTagCateInfoApi,
  saveUserTagCateInfoApi,
  updateUserTagCateInfoApi,
  deleteUserTagCateInfoApi
} from '@/api/userTagCate'
import {
  getUserTagListApi,
  getUserTagInfoApi,
  saveUserTagInfoApi,
  updateUserTagInfoApi,
  deleteUserTagInfoApi
} from '@/api/userTag'

// 当前选中分类
const activeTagCate = ref(1);
// 分类列表
const tagCateList = ref([]);
// 表格数据
const tableData = ref([]);
// 表格数据总数量
const total = ref(0);
// 当前分页
const currentPage = ref(1);
// 项目条数
const pageSize = ref(15);
// 表单对话框
const formShow = ref(false);
// 表单对话框
const formCateShow = ref(false);
// 对话框标题
const dialogTitle = computed(() => (isAdd.value ? '新增标签' : '编辑标签'));
// 对话框标题
const dialogCateTitle = computed(() => (isAdd.value ? '新增分类' : '编辑分类'));
// 提交表单ref
const formDataRef = ref<FormInstance>();
// 分类表单ref
const formCateDataRef = ref<FormInstance>();
// 是否新增
const isAdd = ref(false);

// 接口类型
interface FormDataTypes {
  id?: number
  cate_id: number
  cate_name: string
  status: number
  tag_name: string
}

// 表单数据字段
const initForm = reactive<FormDataTypes>({
  tag_name: '',
  cate_id: null,
  status: 1,
  cate_name: ''
})

// 表单数据字段
const formData = reactive<FormDataTypes>({...initForm})

// 接口类型
interface formCateDataTypes {
  id?: number
  sort: number
  cate_name: string
}

// 分类表单
const formCateData = ref<formCateDataTypes>({
  cate_name: '',
  sort: 1,
});

const rules = ref<FormRules<FormDataTypes>>({
  tag_name: [
    {required: true, message: '标签名称必填', trigger: 'change'},
  ],
  cate_id: [
    {required: true, message: '请选择标签分类', trigger: 'change'},
  ],
});

const cateRules = ref<FormRules<FormDataTypes>>({
  cate_name: [
    {required: true, message: '分类名称必填', trigger: 'change'},
  ],
});

// 状态标签
const statusMap = {
  1: {type: 'primary', text: '启用'},
  0: {type: 'danger', text: '禁用'}
} as const;

const getStatusInfo = (status: number) => statusMap[status] || {type: 'info', text: '未知状态'};

// 打开分类表单对话框
const addCategory = async (isNew, row?: { id: number }) => {
  formCateShow.value = true;
  isAdd.value = isNew;

  // 重置表单
  await nextTick(() => {
    formCateDataRef.value.clearValidate();
    formCateDataRef.value.resetFields();
  });

  formCateData.value = {
    cate_name: '',
    sort: 1
  }

  if (!isAdd.value) {
    const response = await getUserTagCateInfoApi(row.id)
    formCateData.value = response.data
  }
}

// 关闭分类表单对话框
const handleCloseCate = () => {
  formCateShow.value = false;
}

// 左侧分类点击事件
const handleClickTagCate = (tagId) => {
  activeTagCate.value = tagId;
  loadTableData();
};

// 获取标签分类列表
const getUserTagCateList = async () => {
  const response = await getUserTagCateListApi();
  tagCateList.value = response.data;

  activeTagCate.value = tagCateList.value[0]['id'];
  // 加载表格数据
  await loadTableData();
};

// 提交分类表单
const handleCateSubmit = async () => {
  if (!formCateDataRef.value) return;

  // 校验表单
  await formCateDataRef.value.validate();

  // 判断是否为新增或更新
  const isUpdate = !!formCateData.value.id; // 如果存在 id，则为更新操作

  // 执行新增或更新操作
  if (isUpdate) {
    // 更新操作
    await updateUserTagCateInfoApi(formCateData.value.id, formCateData.value);
    ElMessage.success('更新成功');
  } else {
    // 新增操作
    await saveUserTagCateInfoApi(formCateData.value);
    ElMessage.success('新增成功');
  }

  // 关闭对话框并刷新表格数据
  handleCloseCate();
  await getUserTagCateList();
}

// 删除分类数据
const handleDeleteCate = (row) => {
  ElMessageBox.confirm(
      '确定删除此数据吗?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    // 执行删除操作
    await deleteUserTagCateInfoApi(row.id);
    // 刷新分类列表
    await getUserTagCateList();
    // 提示删除成功
    ElMessage({
      type: 'success',
      message: '删除成功',
    });
  })
};

// 加载表格数据
const loadTableData = async () => {
  let params = {
    page: currentPage.value,
    page_size: pageSize.value,
    cate_id: activeTagCate.value
  };
  const response = await getUserTagListApi({
    ...params, // 动态传递分页参数或搜索条件
  });
  tableData.value = response.data.list;
  total.value = response.data.total;
};

// 刷新表格
const handleRefresh = () => {
  currentPage.value = 1; // 重置后也回到第一页
  loadTableData(); // 重新加载初始数据
};

// 删除行数据
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确定删除此数据吗?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    // 执行删除操作
    await deleteUserTagInfoApi(row.id);
    // 刷新表格数据
    await loadTableData();
    // 提示删除成功
    ElMessage({
      type: 'success',
      message: '删除成功',
    });
  })
};

// 表格行数变化处理
const handleSizeChange = async (page: number) => {
  pageSize.value = page;
  await loadTableData()
}

// 分页变化处理
const handleCurrentChange = async (newPage) => {
  currentPage.value = newPage;
  await loadTableData()
};

// 打开对话表单
const openDialogForm = async (isNew: boolean, row?: { id: number }) => {
  formShow.value = true; // 显示对话框
  isAdd.value = isNew;

  Object.assign(formData, initForm);

  await nextTick(() => {
    formDataRef.value.clearValidate();
    formDataRef.value.resetFields();
  });

  if (!isAdd.value) {
    {
      const response = await getUserTagInfoApi(row.id);
      Object.assign(formData, response.data); // 将接口数据合并到 formData 中
    }
  } else {
    formData.cate_id = activeTagCate.value
  }
}

// 关闭对话表单
const handleClose = () => {
  formShow.value = false;
}

// 提交用户表单
const handleSubmit = async () => {
  if (!formDataRef.value) return;

  // 校验表单
  await formDataRef.value.validate();

  // 判断是否为新增或更新
  const isUpdate = !!formData.id; // 如果存在 id，则为更新操作

  // 执行新增或更新操作
  if (isUpdate) {
    // 更新操作
    await updateUserTagInfoApi(formData.id, formData);
    ElMessage.success('更新成功');
  } else {
    // 新增操作
    await saveUserTagInfoApi(formData);
    ElMessage.success('新增成功');
  }

  // 关闭对话框并刷新表格数据
  handleClose();
  await loadTableData();
}

onMounted(() => {
  getUserTagCateList();
})
</script>

<style scoped>
.table-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.table-wrapper {
  flex-grow: 1;
  overflow-y: auto;
  margin-bottom: 10px;
}

.active-tag-cate {
  background-color: var(--el-color-primary-light-9);
  border-right: 2px solid var(--el-color-primary);
}
</style>